#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2023/05/30
# @Author  : locke

# Python接口示例程序

import os,sys,time
import signal
from ctypes import *
from threading import Thread 

# 引入C库
gdl703t = cdll.LoadLibrary('build/libgdl703t.so')

# 管道名称
fifo_r = "/tmp/gdl703t_R_data"
fifo_l= "/tmp/gdl703t_L_data"
global pcm_r_fd
global pcm_l_fd
global is_connect 
# 初始化函数
def init():
    is_connect = 0# 默认断开连接
    # 初始化设备与管道
    gdl703t.gdl703t_init()
    # print('gdl703t.get_is_connect',gdl703t.get_is_connect())
    
    if gdl703t.get_is_connect() == 1:# int字节的0或1
        is_connect =1
        print('已连接 在init函数里面')
         
    if is_connect==1: 
        # 开始获取数据
        gdl703t.gdl703t_start(c_char(b'r'))
    else:
        print('断开连接为假')
        is_connect = 0
        
# 音频数据获取函数 
def data_handle():
    print("=打开录音文件=")
    pcm_f = open("Python_out.pcm","wb+")
    if gdl703t.get_is_connect()!=1:
        os._exit(1)
    else:
            
        # 打开管道
        print("=打开命名管道=")
        pcm_r_fd = os.open(fifo_r,os.O_RDONLY)# 
        
        # pcm_l_fd = os.open(fifo_l,os.O_RDONLY|os.O_SYNC)# 
        
        print("=开始获取数据=")
        while True:
            # print(gdl703t.getDB_char(c_char(b'r')))# 获取分贝值打印
            data = os.read(pcm_r_fd, 1280)
            # print(data)
            # print(len(data),type(data))
            # exit(0)
            # if data != b'':
            if data and  len(data) == 1280:
            
                print('现在1280')
                pcm_f.write(data)
            else:
                if gdl703t.get_is_connect()!=1:
                    # 直接重连
                    print(' 直接重连')
                    gdl703t.gdl703t_init()
                    gdl703t.gdl703t_start(c_char(b'r'))
                    
# 异常处理函数（ctrl+c）
def sigint_handler(signum, frame):
    
    os.close(c_int(pcm_r_fd)) # 关闭管道
    print("Received SIGINT signal!")

# 主函数
if __name__ == '__main__':
    print("gdl703t 设备 python示例程序")
    signal.signal(signal.SIGINT, sigint_handler)
    
    # 创建 Thread 实例
    t1 = Thread(target=init)
    t2 = Thread(target=data_handle)

    # 启动线程运行
    t1.start()
    time.sleep(6)
    t2.start()
    
    while True:
        time.sleep(1)
        # print(gdl703t.getDB_char(c_char(b'r')))# 获取分贝值打印
        # data = os.read(pcm_r_fd, 1280)
        # pcm_f.write(data)
        